package com.cjzuji.rental.controller.excel;

/**
 * @author bag
 * @version V1.0
 * @date 2025/7/4 16:07
 * @since 1.0
 */

import com.cjzuji.rental.Bean.YoupinRequest;
import com.cjzuji.rental.Bean.excelData.YouPingExces;
import com.cjzuji.rental.controller.tool.ToolController;
import com.cjzuji.rental.util.Tool;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 优品二手机
 */
@RestController
@RequestMapping("/excel")
public class YouPinTwo {

    private static final Logger logger = LoggerFactory.getLogger(YouPinTwo.class);


    @GetMapping("/getYouPinList")
    public Object getOrderList(){
        String url = "https://manage-api.qnvipmall.com/merchant/loan/v2/list";
        String accesstoken = "CB31DC1H43V3FF8AIECZB2K17JF3N55LF6G5ARBFH98KFFFF";
        String authorization = "CB31DC1H43V3FF8AIECZB2K17JF3N55LF6G5ARBFH98KFFFF";
        YoupinRequest youpinRequest = new YoupinRequest();
        List<Map<String, Object>> listData = new ArrayList<>();
        youpinRequest.setModel("transferAllList");
        youpinRequest.setPageNo(0);
        youpinRequest.setPageSize(2);
        youpinRequest.setTransferMerchantTag(2);
        int pageNum = 0;  // 从第一页开始
        // 2. 转换为 JSON
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectMapper resMapper = new ObjectMapper();
        while (true) {
            try {
                youpinRequest.setPageNo(pageNum);
                String json = objectMapper.writeValueAsString(youpinRequest);
                logger.info("获取请求参数");
                logger.info(json);
                String resStr = Tool.request(url,accesstoken,authorization,json,"", "");
                logger.info("获取请求结果");
                logger.info(resStr);

                Map<String,Object> res = resMapper.readValue(resStr,Map.class);

                // 获取 data → list
                Map<String, Object> dataMap = (Map<String, Object>) res.get("data");
                List<Map<String, Object>> list = (List<Map<String, Object>>) dataMap.get("list");

                if (list != null && list.size() > 0) {
                    // forEach + Lambda
                    list.stream().forEach(item -> listData.add(item));
//                for (Map<String, Object> item : list) {
//                    listData.add(item);
//                }
                }else {
                    break;
                }
                pageNum ++;
                // 遍历 list
            } catch (JsonProcessingException e) {
                logger.info(e.getMessage());
                break;
            }
        }
        try {
            // 2. 处理数据
            List<YouPingExces> processedList = processData(listData);
            logger.info("数据加密处理完成");
            String outputPath = "youping" + System.currentTimeMillis() + ".xlsx";
            // 3. 生成新的Excel文件并保存到本地
            File outputFile = writeExcelToLocal(processedList, outputPath);
            logger.info("处理后的文件已保存到: {}" ,  outputFile.getAbsolutePath());

            return ResponseEntity.ok("文件处理成功，已保存到: " + outputFile.getAbsolutePath());
        }catch (Exception e){
            return e.getMessage();
        }

    }


    /**
     * 处理数据：对敏感信息进行MD5加密
     */
    public static List<YouPingExces> processData(List<Map<String, Object>> dataList) {
        logger.info("数据list{}",dataList);
        List<YouPingExces> processedList = new ArrayList<>();
        for ( Map<String, Object> data : dataList) {
            logger.info("订单号{}",data.get("no"));
            YouPingExces newData = new YouPingExces();
            newData.setNo((String)data.get("no"));
            newData.setCreateTime((String)data.get("createTime"));
            newData.setTransferRiskTime((String)data.get("transferRiskTime"));
            newData.setMerchantArtificialOpinion((String)data.get("merchantArtificialOpinion"));
            newData.setProductName((String)data.get("productName"));
            newData.setSku((String)data.get("sku"));
            processedList.add(newData);
        }
        return processedList;
    }

    /**
     * 将处理后的数据写入新的Excel文件并保存到本地
     */
    public static File writeExcelToLocal(List<YouPingExces> dataList, String outputPath) throws IOException {
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("订单数据");

            // 创建标题行
            Row headerRow = sheet.createRow(0);
            headerRow.createCell(0).setCellValue("订单号");
            headerRow.createCell(1).setCellValue("下单时间");
            headerRow.createCell(2).setCellValue("取消时间");
            headerRow.createCell(3).setCellValue("风控意见");
            headerRow.createCell(4).setCellValue("商品名称");
            headerRow.createCell(5).setCellValue("商品型号");

            // 填充数据
            for (int i = 0; i < dataList.size(); i++) {
                YouPingExces data = dataList.get(i);
                Row row = sheet.createRow(i + 1);
                row.createCell(0).setCellValue(data.getNo());
                row.createCell(1).setCellValue(data.getCreateTime());
                row.createCell(2).setCellValue(data.getTransferRiskTime());
                row.createCell(3).setCellValue(data.getMerchantArtificialOpinion());
                row.createCell(4).setCellValue(data.getProductName());
                row.createCell(5).setCellValue(data.getSku());
            }

            // 自动调整列宽
            for (int i = 0; i < 4; i++) {
                sheet.autoSizeColumn(i);
            }

            // 创建输出文件
            File outputFile = new File(outputPath);
            try (FileOutputStream fos = new FileOutputStream(outputFile)) {
                workbook.write(fos);
            }

            return outputFile;
        }
    }
}
